<template>
  <div class="collect" ref="collectRef">
    <van-tabs
      class="tabs"
      v-model:active="tabActive"
      color="#1c8cfc"
      sticky
      animated
      swipeable
      @change="onChangeTab"
      :before-change="onBeforeChangeTab"
    >
      <van-tab :title="'宝贝 ' + productTotalCount" :name="1">
        <collect-product-list @change-total-count="changeProductTotalCount" />
      </van-tab>
      <van-tab :title="'文章 ' + articleTotalCount" :name="2">
        <star-product-list @change-total-count="changeArticleTotalCount" />
      </van-tab>
    </van-tabs>
  </div>
</template>

<script setup lang="ts">
import { useScroll } from '@vueuse/core'
import CollectProductList from './components/collect-product-list.vue'
import StarProductList from './components/star-product-list.vue'

const tabActive = ref<number>()
const productTotalCount = ref<number>(0)
const articleTotalCount = ref<number>(0)
const collectRef = ref<HTMLElement>()
const { y } = useScroll(collectRef)
const scrollPosition = reactive([
  {
    id: 1,
    position: 0
  },
  {
    id: 2,
    position: 0
  }
])

const changeProductTotalCount = (count: number) => {
  productTotalCount.value = count
}
const changeArticleTotalCount = (count: number) => {
  articleTotalCount.value = count
}
const onBeforeChangeTab = () => {
  const beforeTab = scrollPosition.find((item) => item.id === tabActive.value)
  if (beforeTab?.id) beforeTab['position'] = y.value
  return true
}
const onChangeTab = async () => {
  const scroll = scrollPosition.find((item) => item.id === tabActive.value)
  if (scroll?.id) {
    setTimeout(() => {
      if (!collectRef.value) return
      collectRef.value.scrollTop = scroll.position
    }, 5)
  }
}

onActivated(() => {
  if (collectRef.value) {
    collectRef.value.scrollTop = y.value
  }
})
</script>

<style lang="scss" scoped>
.collect {
  .tabs {
    :deep(.van-tabs__content) {
      padding: 0 15px;
      height: calc(100% - 44px);
      .van-tab__panel {
        height: 100%;
      }
    }
  }
}
</style>
